package main

import (
	"fmt"
	"github.com/nats-io/nats"
	"log"
	"net/http"
	"os"
	"time"
)

type server struct {
	nc *nats.Conn
}

func (s server) baseRoot(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "NATS 微服务基本示例 v0.0.1")
}

func (s server) healthz(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "OK")
}

func (s server) createTask(w http.ResponseWriter, r *http.Request) {
	requestAt := time.Now()
	response, err := s.nc.Request("task", []byte("help please"), 5*time.Second)
	if err != nil {
		log.Println("ERROR marking NATS request:", err)
	}
	duration := time.Since(requestAt)
	fmt.Fprintf(w, "Task scheduled in %+v\nResponse:%v\n", duration, string(response.Data))
}

func main() {
	var s server
	var err error
	uri := os.Getenv("NATS_URI")
	if uri == "" {
		uri = "nats://localhost:4222"
	}
	nc, err := nats.Connect(uri)
	if err != nil {
		log.Fatal("无法链接到NATS服务器:", err)
	}
	s.nc = nc
	fmt.Printf("成功连接到NATS服务器...(%s)\n", s.nc.ConnectedUrl())

	http.HandleFunc("/", s.baseRoot)
	http.HandleFunc("/healthz", s.healthz)
	http.HandleFunc("/createTask", s.createTask)

	// 开启http服务
	fmt.Println("开启HTTP服务,端口:8080...")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}
